package com.asset.modules.common.utils;
import com.asset.modules.assets.controller.AssetController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {

    private static final Logger LOG = LoggerFactory.getLogger(DateUtils.class);

    /**
     * 常用变量
     */
    public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_YMD = "yyyy-MM-dd";
    public static final String DATE_FORMAT_HMS = "HH:mm:ss";
    public static final String DATE_FORMAT_HM = "HH:mm";
    public static final String DATE_FORMAT_YMDHM = "yyyy-MM-dd HH:mm";
    public static final String DATE_FORMAT_YMDHMS = "yyyyMMddHHmmss";
    public static final String DATE_FORMAT_Y = "yyyy";

    /**
     * 日期转换为制定格式字符串
     *
     * @param time
     * @param format
     * @return
     */
    public static String formatDateToString(Date time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(time);
    }

    //得到当前时间的yyyy-MM-dd HH:mm:ss字符串格式
    public static String getDateTimeNowStr(){
        return formatDateToString(new Date(), DateUtils.DATE_FORMAT_FULL);
    }

    //根据给定时间毫秒数转化为yyyy-MM-dd HH:mm:ss字符串格式
    public static String formatDateTimeStrFromMills(long timemills){
        Date date = new Date();
        date.setTime(timemills);
        return formatDateToString(date, DateUtils.DATE_FORMAT_FULL);
    }


    /**
     * 字符串转换为制定格式日期
     * (注意：当你输入的日期是2014-12-21 12:12，format对应的应为yyyy-MM-dd HH:mm
     * 否则异常抛出)
     * @param date
     * @param format
     * @return
     * @throws ParseException
     *       @
     */
    public static Date formatStringToDate(String date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(date);
        } catch (ParseException ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex.toString());
        }
    }

    /**
     * 计算两个时间点的时间差，以年为单位
     * @param startDate
     * @param endDate
     * @return
     */
    public static Double subtractBetweenDate(String startDate, String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse(startDate);
        Date d2 = sdf.parse(endDate);
        long time = d2.getTime()-d1.getTime();
        DecimalFormat df=new DecimalFormat("0.00");
        String year = df.format((float)(time/(24 * 60 * 60 * 1000))/365);
        LOG.info("时间差是{}",year);
        return Double.valueOf(year);
    }

}
